import React, { useState,useEffect } from 'react';  
import { Table, Button, Modal, Space ,Form,Alert,message,Row,Col, Card} from 'antd';  
import { ExclamationCircleOutlined } from '@ant-design/icons';  
import {useTranslation} from 'react-i18next'
import { createReport,editProduct,separatedFm,addFm,editFm,separatedFix,separatedCreateReport,subjectTestResult,updateSubjectTestResult,mixedfm,mixedFix,mixedCreateReport,getRmInciResult,saveSafetyRmInciResult,batchSaveRmInciResult,updateDataResult,uploadRemark,uploadRemarkUpdate,delRemark,refreshResult} from "@/api/modules/jhreport";
import FullscreenLoading from '@/components/FullscreenLoading';

const Step3 = ({ formData,onUploadSuccess }) => {  
  const { t } = useTranslation();
  const [visible, setVisible] = useState(false);  
  const [rowIndex, setRowIndex] = useState(null);  
  const [columnIndex, setColumnIndex] = useState(null);  
  const [modalValue, setModalValue] = useState(null);  
  const [tableData, setTableData] = useState([]);
  const [errorInfo, setErrorInfo] = useState({  
    composition: [], // 初始化为空数组  
    rows: [],        // 初始化为空数组  
    percentage: 0,   // 初始化为数字0  
  });  
  const [loading, setLoading] = useState(false); 

  useEffect(()=>{
    getData()
  },[])

  const getData = async () => { //formData
    //循环数据
        let i;
        let ii;
        let tableLists = [];
        let seqLength;
        let item;
        let rmItem;
        let temp;
       
        for (i = 0; i < formData.compositionList.length; i++) {
            rmItem = formData.compositionList[i];
            seqLength = rmItem.rm.rmInciList.length;
    
            for (ii = 0; ii < seqLength; ii++) {
                item = formData.compositionList[i].rm.rmInciList[ii];
                temp = {
                    inci_us: item.inci.inciUs,
                    safety_rm_inci_percentage: item.percentage,
                    percentage: rmItem.percentage,
                    inci_cn: item.inci.inciCn,
                    serial: item.inci.serial,
                    remark: item.remark,//rmItem.rm.remark,
                    rm_name: rmItem.rm.rmName,
                    rm_number: rmItem.rm.rmNumber,
                    function_1: rmItem.function1,
                    seq: rmItem.seq
                };
                if (ii == 0 && seqLength > 1) {
                    temp.rowspan = seqLength;
                    }
                if (seqLength == 1) {
                    temp.rowspan = 0;
                    }
                //最后一条打标记
                if (ii == seqLength - 1 && seqLength > 1) {
                    temp.lastRow = 1;
                    }
                    tableLists.push(temp);
                    }
                }
                //整理 tableData

                setTableData(tableLists)
                //整理error
                if (formData.error) {
                    if (formData.error.row) {
                        updateErrorInfo('rows', formData.error.row); 
                    } else {
                        updateErrorInfo('rows', []); 
                    }
                    if (formData.error.serialRm.length>0) {
                        updateErrorInfo('percentage', 1); 
                    } else {
                        updateErrorInfo('percentage', 0); 
                    }
                    if (formData.error.composition) {
                        updateErrorInfo('composition',formData.error.composition); 
                    } else {
                        updateErrorInfo('composition', []); 
                    }
                } else {
                    updateErrorInfo('rows', []);  
                    updateErrorInfo('percentage', 0); 
                    updateErrorInfo('composition', []); 
                }

     
    }

 // 假设你有一个函数来更新 errorInfo 的某个部分  
 const updateErrorInfo = (key, value) => {  
    setErrorInfo((prevErrorInfo) => ({  
      ...prevErrorInfo,  
      [key]: value,  
    }));  
  };  

  const columns = [  
    // 假设这是你的表格其他列...  
    { title: t('report.RMSerial'), dataIndex: 'seq',
     key: 'seq', 
     width:80,
     onCell: (_, index) => {
        const data = getSpanArr(tableData,'seq','seq')
        return {rowSpan : data[index]};
      },  
    },  
    { title: t('report.RMCode'), dataIndex: 'rm_number', key: 'rm_number',
    onCell: (_, index) => {
        const data = getSpanArr(tableData,'seq','rm_number')
        return {rowSpan : data[index]};
      },  
     },  
    { title: t('report.RMName'), dataIndex: 'rm_name', key: 'rm_name' ,
    onCell: (_, index) => {
        const data = getSpanArr(tableData,'seq','rm_name')
        return {rowSpan : data[index]};
      },  
    },  
    { title: t('report.INCICN'), dataIndex: 'inci_cn', key: 'inci_cn' },  
    {  
      title: t('report.INCIEN'),  
      dataIndex: 'inci_us',  
      key: 'inci_us',  
    //   render: (_, record, index) => {  
    //     if (formData.error.composition.includes(index)) {  
    //       return (  
    //         <Space>  
    //              <span>{record.inci_us}</span>  
    //         <ExclamationCircleOutlined style={{ color: 'red' }} />  
    //         <Button onClick={() => handleModify(index, 4)}>修改</Button>  
    //         </Space>  
    //       );  
    //     }  
    //     return <span>{record.inci_us}</span>  ;  
    //   },  
    },  
    {  
      title: t('report.RMPercentage'),    
      dataIndex: 'percentage',  
      key: 'percentage',  
      onCell: (_, index) => {
        const data = getSpanArr(tableData,'seq','percentage')
        return {rowSpan : data[index]};
      },  
    },  
    {  
      title: t('report.IngredientPercentageinRM'),  
      dataIndex: 'safety_rm_inci_percentage',  
      key: 'safety_rm_inci_percentage',  
    },  
    // ...其他列配置  
    { title: t('report.Function'), dataIndex: 'function_1', key: 'function_1' },  
    { title: t('report.remark'), dataIndex: 'remark', key: 'remark',width:80 }, 
  ];  

  // 计算合并单元格的 rowSpan  
  const getSpanArr =(data,dataIndex,dataIndex2) =>{
    let spanArr=[]
    let pos = 0
    // data就是我们从后台拿到的数据
    for (var i = 0; i < data.length; i++) {
      if (i === 0) {
        spanArr.push(1);
        pos= 0;
      } else {
        // 判断当前对象的指定属性值与上一个对象的指定属性值是否相等
        if (data[i][dataIndex] === data[i - 1][dataIndex] ) {
          if (data[i][dataIndex2] === data[i - 1][dataIndex2] ) {
            spanArr[pos] += 1;
            spanArr.push(0);
          } else {
            spanArr.push(1);
            pos = i;
          }
        }else{
          spanArr.push(1);
          pos = i;
        }
      }
    }
    return spanArr
  }
  
//   const handleModify = (rowIndex, columnIndex) => {  
//     setRowIndex(rowIndex);  
//     setColumnIndex(columnIndex);  
//     setVisible(true);  
//     // 假设你可以从 formData 中获取当前行的数据  
//     const rowData = formData.data[rowIndex];  
//     // 根据 columnIndex 获取对应的值  
//     const valueToModify = // 根据 columnIndex 从 rowData 中提取对应的值  
//     setModalValue(valueToModify);  
//   };  
  
  const handleOk = () => {  
    // 调用父组件的 onModify 函数，并传入修改后的值  
    // onModify(rowIndex, columnIndex, modalValue);  
    setVisible(false);  
  };  
  
  const handleCancel = () => {  
    setVisible(false);  
  };  

  const handleSubmit = async () => {  
    setLoading(true)
        let i;
        let ii;
        let tableDataInciLists = {};
        let seqLength;
        let item;
        let rmItem;
        let temp;
        let ai = 0;
        for (i = 0; i < formData.compositionList.length; i++) {
            rmItem = formData.compositionList[i];
            seqLength = rmItem.rm.rmInciList.length;
            let percentageFlag = false;
            
            if(formData.compositionList[i].rm.rmInciList.length == 0){
                message.error("Formula Error:"+ formData.compositionList[i].rm.rmName + "composition is null"); 
            }
            for (ii = 0; ii < seqLength; ii++) {
                if (!percentageFlag) {
                    formData.compositionList[i].percentage = tableData[ai].percentage;
                    percentageFlag = true;
                }
                formData.compositionList[i].rm.rmInciList[ii].inci.inciUs = tableData[ai].inci_us;
                formData.compositionList[i].rm.rmInciList[ii].inci.inciCn = tableData[ai].inci_cn;
                if (tableData[ai].serial) {
                    formData.compositionList[i].rm.rmInciList[ii].inci.serial = tableData[ai].serial;
                    formData.compositionList[i].rm.rmInciList[ii].lawInciSerial = tableData[ai].serial;
                }
                formData.compositionList[i].rm.rmInciList[ii].percentage = tableData[ai].safety_rm_inci_percentage;
                ai++;
            }
            }
            delete formData.error;
                editFm(formData).then(res=>{
                    if(res.data.status == 0){
                        formData = res.data.data
                        getData()
                        if(formData.error){
                            if (formData.error.row.length>0 || formData.error.composition.length>0 || formData.error.serialRm.length>0) { //如果没有错误信息,那么到第四部
                                message.error("失败，请确认"); 
                                setLoading(false)
                            }else{
                                onUploadSuccess("3",res.data.data)
                                setLoading(false)
                            }
                        }else{
                            onUploadSuccess("3",res.data.data)
                            setLoading(false)
                        }
                      
                    }
                }).catch(()=>{
                    
                })
  }

  // 渲染错误提示的函数  
  const renderErrorAlerts = () => {  
    const alerts = [];  
  if(formData.error){
       // 当formData.error.row长度大于0时，循环提示  
       if (formData.error.row.length > 0) {  
        formData.error.row.forEach((rowValue, index) => {  
          alerts.push(  
            <Alert  
              message={`第${rowValue+1}行INCI英文有误，请确认`}  
              type="error"  
              showIcon  
              key={`row-error-${index}`}  
              style={{ marginBottom: 16 }} // 根据需要调整样式  
            />  
          );  
        });  
      }  
    
      // 当formData.error.serialRm长度大于0时，提示百分比加和不为100  
      if (formData.error.serialRm.length > 0) {  
        alerts.push(  
          <Alert  
            message="原料含量百分比加和不为100，请确认"  
            type="error"  
            showIcon  
            key="serial-rm-error"  
            style={{ marginBottom: 16 }} // 根据需要调整样式  
          />  
        );  
      }  
    
      // 当formData.error.composition长度大于0时，循环提示  
      if (formData.error.composition.length > 0) {  
        formData.error.composition.forEach((compositionIndex, index) => {  
          alerts.push(  
            <Alert  
              message={`第${compositionIndex + 1}成分含量有误`} // 假设compositionIndex是从0开始的索引，所以+1使其从1开始  
              type="error"  
              showIcon  
              key={`composition-error-${index}`}  
              style={{ marginBottom: 16 }} // 根据需要调整样式  
            />  
          );  
        });  
      }  
    
      return alerts;  
  }else{
    return ''
  }
 
  };  
  
  return (  
    <>  
    <FullscreenLoading showLoading={loading} loadingTip="Loading..."/> 
    {/* 4是row，5是percentage,6是composition */}
    {/* 渲染错误提示 */}  
    <Card>
    {renderErrorAlerts()}  
      <Table dataSource={tableData} columns={columns}  pagination={false} />  
      <Form onFinish={handleSubmit} layout="vertical">
      <div style={{marginTop:'2%'}}></div>  
      <Row justify="center" align="middle">  
      <Col>  
        <Form.Item>  
        <Button type="primary" htmlType="submit" size='small' >   
          {t('report.Next')}  
        </Button> 
        </Form.Item> 
        </Col> 
        </Row>
      </Form>
    </Card>
  
      <Modal  
        title="修改值"  
        visible={visible}  
        onOk={handleOk}  
        onCancel={handleCancel}  
      >  
        <input  
          type="text"  
          value={modalValue}  
          onChange={(e) => setModalValue(e.target.value)}  
        />  
      </Modal>  
    </>  
  );  
};  
  
export default Step3;